# -*- coding: utf-8 -*-
__author__ = 'liubei'

import json, datetime, time
from mongoengine import *
from bson import *
import types
from itertools import groupby

def encode_model(obj):
    if isinstance(obj, (Document, EmbeddedDocument)):
        out = dict(obj._data)

        for k, v in out.items():
            if isinstance(v, ObjectId):
                out[k] = str(v)
            if isinstance(v, datetime.datetime):
                out[k] = int(time.mktime(v.timetuple()))
            if isinstance(v, list):
                tmpList = []
                for i in v:
                    tmpList.append(encode_model(i))
                out[k] = tmpList
    elif isinstance(obj, QuerySet):
        out = list(obj)
    elif isinstance(obj, types.ModuleType):
        out = None
    elif isinstance(obj, groupby):
        out = [(g,list(l)) for g,l in obj]
    else:
        raise TypeError, "Could not JSON-encode type '%s': %s" % (type(obj), str(obj))

    return out


from mongoengine import StringField, ListField, IntField, FloatField


def mongo_to_dict_helper(obj):
    return_data = []
    for field_name in obj._fields:
        if field_name in ("id",):
            continue
        data = obj._data[field_name]
        if isinstance(obj._fields[field_name], StringField):
            return_data.append((field_name, str(data)))
        elif isinstance(obj._fields[field_name], FloatField):
            return_data.append((field_name, float(data)))
        elif isinstance(obj._fields[field_name], IntField):
            return_data.append((field_name, int(data)))
        elif isinstance(obj._fields[field_name], ListField):
            return_data.append((field_name, data))
        else:
            pass
            #You can define your logic for returning elements
    return dict(return_data)